import { getRequest } from "../utils/request";

export const initMenu = (router, store) => {
  if (store.state.routes.length > 0) {
      return
  }
  getRequest('/system/cfg/menu').then(data => {
      if (data) {
        //   console.log(data,'22');
          // 格式化Router
          let fmtRoutes = formatRoutes(data);
          console.log(fmtRoutes,'final');
          // 添加到router
          router.addRoutes(fmtRoutes);
          //将数据存入Vuex
          store.commit('initRoutes', fmtRoutes)
          // 连接WebSocket
          store.dispatch('connect')
      }
  })
}

export const formatRoutes = (routes) => {
  let fmtRoutes = [];
  routes.forEach(router => {
      let {
          path,
          component,
          name,
          iconCls,
          children,
      } = router;
      if (children && children instanceof Array) {
          // 递归
          children = formatRoutes(children)
      }
      let fmRouter = {
          path: path,
          name: name,
          iconCls: iconCls,
          children: children,
          component(resolve) {
              if (component.startsWith('Home')){
                  console.log('../views/' + component + '.vue');
                  // views/Home.vue
                  require(['../views/' + component + '.vue'], resolve)
              } else if (component.startsWith('Emp')){
                  // views/emp/EmpBasic.vue
                  require(['../views/emp/' + component + '.vue'], resolve)
              } else if (component.startsWith('Per')){
                  require(['../views/per/' + component + '.vue'], resolve)
              } else if (component.startsWith('Sal')){
                  require(['../views/sal/' + component + '.vue'], resolve)
              } else if (component.startsWith('Sta')){
                  require(['../views/sta/' + component + '.vue'], resolve)
              } else if (component.startsWith('Sys')){
                  require(['../views/sys/' + component + '.vue'], resolve)
              }
          }
      }
    //   console.log(fmRouter);
      fmtRoutes.push(fmRouter)
  });
  return fmtRoutes;
}